package com.zhang.boot.core.security;

import com.zhang.boot.core.annotation.Decrypt;
import com.zhang.boot.core.constants.ErrorEnum;
import com.zhang.boot.core.exception.BusinessException;
import com.zhang.boot.web.config.SecretKeyConfig;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpInputMessage;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.RequestBodyAdvice;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @Author zhangshaobin
 * @Date 2020/10/30
 * @Description
 */
@Slf4j
@ControllerAdvice
@RequiredArgsConstructor
public class EncryptRequestBodyAdvice implements RequestBodyAdvice {
    private final SecretKeyConfig secretKeyConfig;
    //ThreadLocal<Boolean> encryptThreadLocal = new ThreadLocal<>();

    @Override
    public boolean supports(MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        Boolean encrypt = false;
        boolean decryptFlag = methodParameter.getMethod().isAnnotationPresent(Decrypt.class);
        if (decryptFlag && !secretKeyConfig.isDebug()) {
            encrypt = true;
        }
        //encryptThreadLocal.set(encrypt);
        return encrypt;
    }

    @Override
    public HttpInputMessage beforeBodyRead(HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) throws IOException {
        //if (encryptThreadLocal.get()) {
            try {
                return new DecryptHttpInputMessage(httpInputMessage, this.secretKeyConfig.getPrivateKey(), this.secretKeyConfig.getCharset());
            } catch (Exception e) {
                throw new BusinessException(ErrorEnum.DECRYPTION_FAILED);
            }
        //}
        //return httpInputMessage;
    }

    @Override
    public Object afterBodyRead(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }

    @Override
    public Object handleEmptyBody(Object body, HttpInputMessage httpInputMessage, MethodParameter methodParameter, Type type, Class<? extends HttpMessageConverter<?>> aClass) {
        return body;
    }
}
